package com.itheima.exception;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.qiniu.util.Json;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class MyException implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        if (ex instanceof AccessDeniedException) {
//            FastJsonJsonView view = new FastJsonJsonView();
//            Map<String, Object> attributes = new HashMap<String, Object>();
//            attributes.put("flag", false);
//            attributes.put("message", "您无操作权限");
//            view.setAttributesMap(attributes);
//            modelAndView.setView(view);
//            }
            /*  使用response返回    */
//            response.setStatus(HttpStatus.OK.value()); //设置状态码
//            response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
//            response.setCharacterEncoding("UTF-8"); //避免乱码
//            response.setHeader("Cache-Control", "no-cache, must-revalidate");
            try {
                Result result = new Result(false, MessageConstant.HAVE_NO_PERMISSION);
//                response.getWriter().write("{\"flag\":false,\"message\":\"" + "您无操作权限" + "\"}");
//                response.getWriter().write("{\"flag\":false,\"message\": '您无操作权限'}");
                String jsonString = JSON.toJSONString(result);
                response.getWriter().write(jsonString);
//                String contextPath = request.getContextPath();
//                String servletPath = request.getServletPath();
//                String realPath = request.getSession().getServletContext().getRealPath("/");
//                System.out.println(contextPath);
//                System.out.println(servletPath);
//                System.out.println(realPath);
//                response.sendRedirect("/hello.html");
            } catch (IOException e) {
            }
        }
        return modelAndView;
    }
}
